import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { StartupService } from '@core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';
import { PublicService } from 'src/app/shared/service/public.service';

@Component({
  selector: 'app-tenant-drawer',
  template: ` <button nz-button nzType="primary" (click)="open()">{{ tenantInfo.shortName || '请选择租户' }}</button>
    <nz-drawer [nzClosable]="false" [nzVisible]="visible" nzPlacement="right" nzTitle="切换租户" (nzOnClose)="close()">
      <ng-container *nzDrawerContent>
        <div *ngFor="let item of tenantList">
          <nz-card nzTitle="{{ item.name }}" [nzExtra]="extraTemplate">
            <p>{{ item.name }}</p>
          </nz-card>
          <ng-template #extraTemplate>
            <button *ngIf="tenantInfo.id !== item.id" nz-button nzType="primary" (click)="change(item)" [nzLoading]="isLoadingOne"
              >切换</button
            >
          </ng-template>
        </div>
      </ng-container>
    </nz-drawer>`
})
export class TenantDrawerComponent implements OnInit {
  constructor(
    protected http: _HttpClient,
    private router: Router,
    private publicService: PublicService,
    protected settingsService: SettingsService,
    public startupSvr: StartupService
  ) {}

  visible = false;
  isLoadingOne = false;
  tenantInfo: any = {};
  tenantList: any = [];
  @Output() readonly callback: EventEmitter<Event> = new EventEmitter();
  open(): void {
    this.visible = true;
  }

  close(): void {
    this.visible = false;
  }

  ngOnInit(): void {
    const tenantInfo = this.publicService.getCurrentTenant();
    if (!tenantInfo) {
      // this.getJoinedTenantList();
      return;
    }
    if (!this.tenantInfo) {
      this.tenantInfo = {};
      this.router.navigate(['/tenant/info']);
      return;
    }
    // this.getJoinedTenantList();
  }

  change(item: any) {
    this.tenantInfo = item;
    this.publicService.setCurrentTenant(JSON.stringify(item));
    if (this.callback) this.callback.emit();
    this.visible = false;
  }

  getJoinedTenantList() {
    const userId = this.settingsService.user['id'];
    const param = { userId: userId };
    this.http.get(`${Api.BaseSysTenantApi}user/tenant/id`, param).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) {
          this.tenantList = res.data;
          if (this.tenantList.length > 0) {
            if (this.tenantInfo) {
              let contained = false;
              for (const item of this.tenantList) {
                if (item.id === this.tenantInfo.id) {
                  contained = true;
                  break;
                }
              }
              if (!contained) {
                this.tenantInfo = this.tenantList[0];
                this.publicService.setCurrentTenant(JSON.stringify(this.tenantInfo));
              }
            } else {
              this.tenantInfo = this.tenantList[0];
              this.publicService.setCurrentTenant(JSON.stringify(this.tenantInfo));
            }
            this.startupSvr.load();
          } else {
            this.tenantInfo = {};
          }
        } else {
          this.tenantInfo = {};
        }
      }
      this.callback.emit();
    });
  }
}
